<script setup lang="ts">
import { deleteOrderApi, getOrderListApi } from '@/api/order'
import type { orderListResult } from '@/types/order'
import { ref, watch } from 'vue'
import {
  orderState,
  orderStateList,
  orderType,
  orderStateActions,
  refundStateList,
  pageUrl,
} from '@/utils/constants'
import { fullUrl, getPayPageUrl } from '@/utils/common'
import { onShow } from '@dcloudio/uni-app'
import cancelButton from '@/pagesOrder/components/cancelButton.vue'
import { usePupupStore } from '@/stores'
import ReceiveButton from '@/pagesOrder/components/receiveButton.vue'
import type { orderResult } from '@/types/order'
import { createStripePaymentIntentApi, type StripeApiResponse } from '@/api/stripe'

// eslint-disable-next-line no-undef
const paging = ref<ZPagingInstance>()
const dataList = ref<orderListResult[]>([])
// 当前组件是否已经加载过了
const firstLoaded = ref(false)
// 是否滚动到当前页
const isCurrentPage = ref(false)

const props = withDefaults(
  defineProps<{
    tabIndex: number
    currentIndex: number
    status: string
  }>(),
  {
    tableIndex: 0,
    currentIndex: 0,
    status: '',
  },
)
const queryList = (page: number, page_size: number) => {
  const params = {
    page,
    page_size,
    type: orderType.default,
    status: props.status,
  }
  getOrderListApi(params).then((res) => {
    res.result.data.map((item) => {
      if (item.status == orderState.toPay && item.countdown < 0) {
        item.status = orderState.canceled
      }
    })
    paging.value?.complete(res.result.data)
  })
}

// 删除订单
const onDeleteOrder = (id: number) => {
  uni.showModal({
    content: 'Are you sure you want to delete this order?',
    cancelText: 'Cancel',
    confirmText: 'Confirm',
    success: (res) => {
      if (res.confirm) {
        deleteOrderApi({
          id: [id],
        }).then(() => {
          uni.showToast({
            title: 'Successfully deleted',
            icon: 'success',
          })
          setTimeout(() => {
            paging.value?.refresh()
          }, 1000)
        })
      }
    },
  })
}

const onCancel = (event: { orderId: number; reason: string }) => {
  const index = dataList.value.findIndex((v) => v.id == event.orderId)
  if (index > -1) {
    dataList.value.splice(index, 1)
  }
}

const onPay = async (detailData: orderResult) => {
  // sharePopupRef.value?.open()

  //判断如果是网页h5环境，则提示请前往app支付
  // #ifdef H5
  uni.showModal({
    title: 'Payment Notice',
    content: 'Please use our mobile app for a better payment experience.',
    showCancel: false,
    confirmText: 'OK'
  });
  // #endif

  // #ifdef APP-PLUS
  if (!detailData) {
    console.error("Order details not available for payment preparation.");
    uni.showToast({ title: 'Order details not available', icon: 'none' });
    return;
  }

  try {
    // Call your new API to get payment intent
    // Runtime error "No result object" suggests that 'createStripePaymentIntentApi'
    // returns StripeApiResponse directly, not wrapped in a '.result' property.

    if (!detailData || !detailData.detail || detailData.detail.length === 0) {
      console.error("Order details or product details not available for payment preparation.");
      uni.showToast({ title: 'Order/Product details not available', icon: 'none' });
      return;
    }

    // Calculate total price from items in detailData.detail
    let itemsTotalPrice = 0;
    for (const item of detailData.detail) {
      itemsTotalPrice += Number(item.price) * Number(item.num);
    }

    // Subtract coupon discount
    // Assuming detailData.discount_data.coupon_discount is a positive number representing the discount amount
    const couponDiscount = Number(detailData.discount_data?.coupon_discount || 0);
    const finalAmountToPay = itemsTotalPrice - couponDiscount;

    if (finalAmountToPay < 0) {
      console.error("Final amount to pay is negative after discount:", finalAmountToPay);
      uni.showToast({ title: 'Error in calculating amount', icon: 'none' });
      return;
    }

    const currency = 'USD'; // Assuming USD, please confirm or change
    // Convert final calculated amount to cents
    const amountInCents = String(finalAmountToPay);
    const currentOrderId = String(detailData.id);

    console.log('[Debug] Preparing payment intent with (calculated based on items):', {
      currency: currency,
      amount: amountInCents,
      order_id: currentOrderId,
      items_total_price_before_discount: itemsTotalPrice,
      coupon_discount_applied: couponDiscount,
      final_amount_to_pay_before_cents_conversion: finalAmountToPay,
      original_order_pay_price: detailData.pay_price // For comparison/debugging
    });

    const apiResponseDirectly = await createStripePaymentIntentApi({
      currency: currency,
      amount: amountInCents,
      order_id: currentOrderId,
    });

    // Log the direct response to see its structure.
    // This is what we believe IS the StripeApiResponse.
    console.log("Direct API Response from createStripePaymentIntentApi:", JSON.stringify(apiResponseDirectly));

    // Now, we assert that apiResponseDirectly IS the StripeApiResponse.
    // If the linter complains here that apiResponseDirectly (e.g. if typed as Data<StripeApiResponse>)
    // doesn't have .code, .data, it means the type definition of createStripePaymentIntentApi
    // or the underlying 'request' utility is inconsistent with runtime behavior.
    // Forcing the type for now to align with runtime evidence.
    const stripeApiActualResponse = apiResponseDirectly as unknown as StripeApiResponse;


    // Check for successful API response
    const isResponseValid = stripeApiActualResponse &&
                            stripeApiActualResponse.code === 200 &&
                            stripeApiActualResponse.data;

    if (!isResponseValid) {
      let errorMsg = 'Failed to create payment intent';
      if (!stripeApiActualResponse) {
          errorMsg += ' (API response is null, undefined, or not a valid StripeApiResponse structure after casting)';
          console.error("Failed Payment Intent: API response is problematic:", JSON.stringify(apiResponseDirectly));
      } else if (stripeApiActualResponse.code !== 200) {
          errorMsg += ` (API Code: ${stripeApiActualResponse.code}, Sent Amount: ${amountInCents} cents, Msg: ${stripeApiActualResponse.msg || 'N/A'})`;
          console.error("Failed Payment Intent: Invalid code:", JSON.stringify(stripeApiActualResponse), "Sent amount in cents:", amountInCents);
      } else if (!stripeApiActualResponse.data) {
          errorMsg += ' (Missing data field)';
          console.error("Failed Payment Intent: Missing data field:", JSON.stringify(stripeApiActualResponse));
      } else {
          errorMsg += ' (Unknown structure issue after basic checks)';
          console.error("Failed Payment Intent: Unknown structure issue:", JSON.stringify(stripeApiActualResponse));
      }

      uni.showToast({ title: errorMsg, icon: 'none', duration: 5000 });
      return;
    }

    const paymentData = stripeApiActualResponse.data; // Access data from the actual response

    const orderInfo = {
        "customer": paymentData.customer,
        "ephemeralKey": paymentData.ephemeralKey,
        "isAllowDelay": true, 
        "merchantName": "DCloud", 
        "paymentIntent": paymentData.paymentIntent,
        "publishKey": paymentData.publishableKey, // Mapped from publishableKey
        "billingDetails":{
            "name": detailData.address?.name || "",
            "email": "", // Add email if available, e.g., detailData.user_email
            "phone": detailData.address?.phone || "",
            "address":{
                "city": "", // Was detailData.address?.city_name - property does not exist
                "country": detailData.address?.country_code || "US", // Use country_code from address, or default to 'US'
                "line1": detailData.address?.full_address || "", // Was detailData.address?.address - property does not exist, using full_address
                "line2": "",
                "postalCode": "", // Was detailData.address?.postal_code - property does not exist
                "state": "" // Was detailData.address?.province_name - property does not exist
            }
        }
    };

    //获取支付渠道 和 发起支付 (仅在 App 环境下执行)
    // #ifdef APP-PLUS
    plus.payment.getChannels(function(channels: any[]){ // Added type for channels
        let stripeSev: any = null; // Initialize stripeSev with null and specific type
        for (var i in channels) {
            var channel = channels[i];
            if (channel.id === 'stripe') {
                stripeSev = channel;
                break; // Found stripe, no need to continue loop
            }
        }

        if (!stripeSev) {
            console.error("Stripe payment channel not found.");
            uni.showToast({ title: 'Stripe payment channel not found', icon: 'none' });
            return;
        }

        //发起支付
        plus.payment.request(stripeSev, orderInfo, function(result: { rawdata?: string }) { // Added type for result
             if (result.rawdata) {
               const rawdata = JSON.parse(result.rawdata);
               console.log("支付成功", rawdata);
               // Optionally, navigate to a success page or refresh order details
               uni.showToast({ title: 'Payment Successful', icon: 'success' });
               getDetailData(); // Refresh order details
             } else {
               console.error("Payment successful but no rawdata received:", result);
               uni.showToast({ title: 'Payment issue: No data', icon: 'none' });
             }
        }, function(e: any) { // Added type for e
             console.log("支付失败：" + JSON.stringify(e));
            //  uni.showToast({ title: 'Payment Failed: ' + (e.message || JSON.stringify(e)), icon: 'none' });
        });
      }, function(e: any){ // Added type for e
          console.log("获取支付渠道失败：" + JSON.stringify(e));
          uni.showToast({ title: 'Failed to get payment channels', icon: 'none' });
    });
    // #endif

    // #ifndef APP-PLUS
    console.warn('Payment via plus.payment is only available in APP environment.');
    uni.showToast({ title: 'Payment not supported in this environment', icon: 'none' });
    // #endif

  } catch (error: any) {
    console.error("Error in onPay:", error);
    uni.showToast({ title: 'Error during payment: ' + (error.message || 'Unknown error'), icon: 'none' });
  }

  // #endif
}

watch(
  () => props.currentIndex,
  (newVal) => {
    if (newVal === props.tabIndex) {
      // 懒加载，当滑动到当前的item时，才去加载
      if (!firstLoaded.value) {
        // 这里需要延迟渲染z-paging的原因是为了避免在一些平台上立即渲染可能引发的底层报错问题
        setTimeout(() => {
          isCurrentPage.value = true
        }, 100)
      }
    }
  },
  {
    immediate: true,
  },
)

onShow(() => {
  if (props.currentIndex === props.tabIndex) {
    paging.value?.refresh()
  }
})

const backToTop = ref(true)
watch(
  () => usePupupStore().showCancelPopup,
  (newVal) => {
    backToTop.value = !newVal
  },
  { immediate: true },
)
</script>

<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
  <view class="content">
    <!-- 如果当前页已经加载过数据或者当前切换到的tab是当前页，才展示当前页数据（懒加载） -->
    <z-paging
      :enable-back-to-top="currentIndex === tabIndex"
      v-if="firstLoaded || isCurrentPage"
      ref="paging"
      v-model="dataList"
      @query="queryList"
      :fixed="false"
      :auto-show-back-to-top="backToTop"
      :back-to-top-style="{
        display: backToTop ? '' : 'none',
      }"
      bg-color="#f6f6f6"
    >
      <view class="orders" v-for="(item, index) in dataList" :key="index">
        <view class="card">
          <view class="status">
            <text class="date">{{ item.create_time }}</text>
            <text v-if="item.status === orderState.applyCancel">
              {{ refundStateList.find((v) => v.id == item.refund_status)?.text ?? '' }}
            </text>
            <text v-else>{{ orderStateList[item.status].text ?? '' }}</text>
            <text
              class="icon-delete"
              v-show="orderStateActions.deletable.includes(item.status)"
              @tap="onDeleteOrder(item.id)"
            />
          </view>

          <navigator
            v-for="sku in item.detail"
            :key="sku.id"
            class="goods"
            :url="`${pageUrl['order-detail']}?id=${item.id}`"
            hover-class="none"
          >
            <image class="cover" :src="fullUrl(sku.image)"></image>

            <view class="meta">
              <view class="name ellipsis">
                <text class="name-text">{{ sku.goods_name }}</text>
                <text class="price"> <text class="symbol">$</text>{{ sku.price }}</text>
              </view>
              <!-- <view class="name meta-spec">{{ sku.spec.split('，')[1] }}</view> -->
              <view class="meta-spec" v-if="sku.spec">
                <view class="color">
                  <text>Color：</text>
                  <image class="color" :src="fullUrl(sku.spec.split('，')[0])" alt="" />
                </view>
                <view class="size">
                  <text>Size：</text>{{ sku.spec.split('，')[1] }}
                </view>
              </view>
              <view class="meta-quantity">x{{ sku.num }}</view>
            </view>
          </navigator>

          <view class="payment">
            <text class="quantity">Total {{ item.total_num }} items</text>
            <text class="tit" v-if="orderStateActions.normalTransaction.includes(item.status)">Paid</text>
            <text class="tit" v-else>To Pay: </text>
            <text class="amount"> <text class="symbol">$</text>{{ item.pay_price }}</text>
          </view>

          <view class="action">
            <template v-if="item.status === orderState.toPay && item.countdown > 0">
              <view>
                <text class="pay-time">Payment Time Left :</text>
                <countdown-timer :time="item.countdown * 1000" :autoStart="true">
                  <template v-slot="{ day, hour, minute, second }">
                    <view v-if="item.countdown > 86400">{{ day }} days {{ hour }} hrs {{ minute }} mins</view>
                    <view v-else-if="item.countdown < 60">{{ second }} secs</view>
                    <view v-else>{{ hour }} hrs {{ minute }} mins</view>
                  </template>
                </countdown-timer>
              </view>
              <view class="flex-end">
                <cancelButton
                  :status="item.status"
                  :id="item.id"
                  className="button secondary"
                  @cancel="onCancel"
                />
                <!-- <navigator
                  class="button primary"
                  :url="getPayPageUrl(item.id, item.pay_price)"
                  hover-class="none"
                >
                  Pay Now
                </navigator> -->
                <button class="button primary" @tap="onPay(item)">Pay Now</button>
              </view>
            </template>
            <template v-else>
              <view  class="flex-end">
                <cancelButton
                  :status="item.status"
                  :id="item.id"
                  className="button secondary"
                  @cancel="onCancel"
                />

                <ReceiveButton
                  :status="item.status"
                  :id="item.id"
                  :paymentTradeInfo="item.payment_trade"
                  className="button secondary"
                />
              </view>
              <view class="flex-end">
                  <view v-if="orderStateActions.evaluatable.includes(item.status)">
                  <navigator
                    :url="`${pageUrl['order-evaluate']}?order_id=${item.id}`"
                    class="button secondary"
                    hover-class="none"
                  >
                    Review
                  </navigator>
                </view>

                <navigator
                  class="button primary"
                  :url="`${pageUrl['order-create']}?orderId=${item.id}`"
                  hover-class="none"
                >
                  Buy Again
                </navigator>
              </view>
            </template>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<style scoped lang="scss">
/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
.content {
  height: 100%;
}
page {
  background-color: #f6f6f6;
}
.orders {
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;

  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .name {
      font-size: 26rpx;
      color: #444;
      // max-width: 90%;
      display: flex;
      justify-content: space-between;
      .name-text{
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .price{
        font-size: 26rpx;
        padding-left: 10rpx;
      }
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;

      .symbol {
        font-size: 80%;
        margin-left: 4rpx;
        position: relative;
      }

      .meta-spec{
        background: transparent;
        display: flex;
        align-items: center;
        font-size: 24rpx;
        color: #888;
        span{
          font-size: 24rpx;
        }
        .color{
          margin-right: 20rpx;
          image{
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
            border: 1px solid #e3e3e3;
          }
        }
      }

      &-quantity {
        position: absolute;
        right: 20px;
        font-size: 24rpx;
        color: #9e9c9c;
      }
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
      font-size: 32rpx;
      font-weight: bold;
    }

    .symbol {
      font-size: 24rpx;
      margin-left: 4rpx;
      font-weight: bold;
      position: relative;
      top: -2px;
    }
    .tit{
      font-size: 24rpx;
      color: #444;
    }
  }

  .action {
    display: flex;
    justify-content: space-between;
    // align-items: center;
    padding-top: 20rpx;
    line-height: 35rpx;
    .pay-time {
      font-size: 24rpx;
      color: #999;
      margin-right: 20rpx;
    }

    .countdown {
      font-size: 24rpx;
      color: #999;
      margin-left: auto;
      display: flex;
    }

    .flex-end{
      display: flex;
      justify-content: flex-end;
    }

    .button {
      width: 170rpx;
      height: 60rpx;
      line-height: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ff5f3c;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #ff5f3c;
      border-color: #ff5f3c;
    }

    .primary {
      color: #fff;
      background-color: #ff5f3c;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
